﻿using System;
using System.IO;
using System.Text;
using System.Web.Mvc;

namespace MvcApplication7
{
    public class HtmlUpdateInfo
    {
        private readonly string divId;
        private readonly string html;

        public string DivId
        {
            get { return divId; }
        }

        public string Html
        {
            get { return html; }
        }

        public HtmlUpdateInfo(string divId, string html)
        {
            this.divId = divId;
            this.html = html;
        }
    }

    public static class ControllerExtensions
    {
        public static string RenderPartialViewToString(this Controller it, string viewName, object model)
        {
            if (String.IsNullOrEmpty(viewName))
                viewName = it.ControllerContext.RouteData.GetRequiredString("action");

            it.ViewData.Model = model;

            var stringBuilder = new StringBuilder();
            using (var writer = new StringWriter(stringBuilder))
            {
                var viewEngineResult = ViewEngines.Engines.FindPartialView(it.ControllerContext, viewName);
                viewEngineResult.View.Render(
                    new ViewContext(
                        it.ControllerContext,
                        viewEngineResult.View,
                        it.ViewData,
                        it.TempData,
                        writer),
                    writer);
            }
            return stringBuilder.ToString();
        }

        public static HtmlUpdateInfo GetHtmlUpdateInfo(this Controller it, string divId, string viewName, object model)
        {
            return new HtmlUpdateInfo(divId, it.RenderPartialViewToString(viewName, model));
        }
    }
}